package org.example.api.window;

import org.apache.commons.collections.IteratorUtils;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.example.api.bean.SensorReading;

/**
 * @author huangqihan
 * @date 2021/2/20
 */
public class TimeWindowTest {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        String host = "localhost";
        int port = 7777;

        // Use NetCat to read the data source. nc -lp 7777
        DataStreamSource<String> inputStream = env.socketTextStream(host, port);

        SingleOutputStreamOperator<SensorReading> mapStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 1.Incremental aggregation functions
        // ReduceFunction, AggregationFunction
        // Count when every record arrived
        DataStream<Integer> resultStream = mapStream.keyBy("id")
                .timeWindow(Time.seconds(15))
                //      .countWindow(10);
                //      .countWindow(10, 2);
                //      .window(EventTimeSessionWindows.withGap(Time.seconds(60)));
                //      .window(TumblingAlignedProcessingTimeWindows.of(Time.seconds(15)));
                .aggregate(
                        new AggregateFunction<SensorReading, Integer, Integer>() {
                            @Override
                            public Integer createAccumulator() {
                                // initial value
                                return 0;
                            }

                            @Override
                            public Integer add(SensorReading s, Integer i) {
                                return i + 1;
                            }

                            @Override
                            public Integer getResult(Integer i) {
                                return i;
                            }

                            @Override
                            public Integer merge(Integer a, Integer b) {
                                return a + b;
                            }
                        });

        // 2.Full window functions
        // Count when the time is up
        // ProcessWindowFunction, WindowFunction
        SingleOutputStreamOperator<Tuple3<String, Long, Integer>> resultStream1 = mapStream.keyBy("id")
                .timeWindow(Time.seconds(15))
//                .process(new ProcessWindowFunction<SensorReading, Object, Tuple, TimeWindow>() {
//                })
                .apply(new WindowFunction<SensorReading, Tuple3<String, Long, Integer>, Tuple, TimeWindow>() {
                    @Override
                    public void apply(Tuple tuple, TimeWindow timeWindow, Iterable<SensorReading> input, Collector<Tuple3<String, Long, Integer>> output) throws Exception {
                        Integer count = IteratorUtils.toList(input.iterator()).size();
                        // Integer count = (int) IterableUtils.toStream(input).count();
                        String id = tuple.getField(0);
                        long end = timeWindow.getEnd();
                        output.collect(new Tuple3<>(id, end, count));
                    }
                });

        // 3.other api
//        OutputTag<SensorReading> outputTag = new OutputTag<>("late");
//        SingleOutputStreamOperator<SensorReading> sumStream = mapStream.keyBy("id")
//                .timeWindow(Time.seconds(15))
//                .allowedLateness(Time.minutes(1))
//                .sideOutputLateData(outputTag)
//                .sum("temperature");
//        sumStream.getSideOutput(outputTag);

        resultStream.print("0");
//        resultStream1.print("1");
        env.execute();
    }
}
